//
//  SideMenuView.swift
//  STest
//
//  Created by wang tiao on 2025/9/3.
//


import UIKit


class SideMenuView: UIView {
    
    let menuWidth: CGFloat = 300
    private var isOpen = false
    
    let overlayView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        view.alpha = 0
        return view
    }()
    
    let menuView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private var parentView: UIView!
    
    init(parent: UIView) {
        super.init(frame: parent.bounds)
        self.parentView = parent
        setupViews()
        setupGesture()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupGesture() {
        // 覆盖整个 view 的 pan 手势
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
        addGestureRecognizer(panGesture)
    }
    
    @objc private func handlePan(_ gesture: UIPanGestureRecognizer) {
        
        let translation = gesture.translation(in: parentView)
        let velocity = gesture.velocity(in: parentView)
        
        switch gesture.state {
        case .changed:
            // 菜单跟随手势滑动
            var x = menuView.frame.origin.x + translation.x
            x = max(-menuWidth, min(0, x)) // 限制左右边界
            menuView.frame.origin.x = x
            
            // 遮罩透明度
            overlayView.alpha = (menuWidth + x) / menuWidth * 0.5

            gesture.setTranslation(.zero, in: self)
        case .ended:
            if velocity.x > 300 {
                openMenu()
            } else if velocity.x < -300 {
                closeMenu()
            } else {
                // 根据菜单位置决定开关
                menuView.frame.origin.x > -menuWidth/2 ? openMenu() : closeMenu()
            }
        default:
            break
        }
    }
    
    private func setupViews() {
        overlayView.frame = parentView.bounds
        menuView.frame = CGRect(x: -menuWidth, y: 0, width: menuWidth, height: parentView.bounds.height)
        
        addSubview(overlayView)
        addSubview(menuView)

        // 点击遮罩关闭
        let tap = UITapGestureRecognizer(target: self, action: #selector(closeMenu))
        overlayView.addGestureRecognizer(tap)
    }
    
    func openMenu() {
        UIView.animate(withDuration: 0.3) {
            self.menuView.frame.origin.x = 0
            self.overlayView.alpha = 0.5
        }
        isOpen = true
    }
    
    @objc func closeMenu() {
        UIView.animate(withDuration: 0.3, animations: {
            self.menuView.frame.origin.x = -self.menuWidth
            self.overlayView.alpha = 0
        }) { _ in
            self.removeFromSuperview()
        }
        isOpen = false
    }
}
